<?php

namespace app\api\controller;
use Throwable;
use think\facade\Db;
use think\facade\Request;
use app\admin\model\Admin;
use app\admin\model\UserVip;
use app\admin\model\Order;
use app\admin\model\Message;
use app\admin\model\Distributor;
use app\admin\model\DeviceDistributor;
use app\admin\model\RechargeSetting;
use app\admin\model\RechargeSpace;
use app\admin\model\User as UserModel;
use app\api\service\userService;
use app\api\validate\Admin as AdminValidate;
use app\common\controller\Api;
class Agent extends Api
{ 

	// 初始化方法（自动执行）
    protected function initialize(): void
    {
	       parent::initialize(); // 调用父类初始化（可选）  
	       $this->params = $this->request->post("");
	       $admin = Admin::where("id",request()->adminId)->where("status","enable")->find();
	       if($admin){
               if(!in_array(7, $admin['group_arr'])){
               	  //$this->error("无权限");
               }
            }else{
            	  $this->error("账号异常");
            }
	      
    }
    //获取反馈列表
    function feedback(){
       $status = $this->params['status'] ?? '';
       $phoneKeyword = $this->params['key'] ?? '';
       $w['m.agent_id'] = request()->adminId;
       $w['m.rid'] = 0;
       if($status == 2){
           $w['m.status'] = 0;
       }
       if($status == 1){
           $w['m.status'] = 1;
       }

       if($phoneKeyword){

            $lists = Message::alias('m')
                    ->join('user u', 'u.id = m.uid')
                    ->where($w)
                    ->where('u.mobile', 'like', '%' . $phoneKeyword . '%')
                    ->order("m.id desc")
                    ->select();
       }else{

            $lists = Message::alias('m')->where($w)->order("id desc")->select();
       }

       
       return json(['code'=>200,'data'=>$lists ?? []]);
    }

    //反馈详细
    function feedbackDetail(){
         $id = $this->request['id'] ?? 0;
         $res = Message::with(['user'])->where(['agent_id'=>request()->adminId,'id'=>$id])->find();
         if(!$res){
              return json(['code'=>100,'msg'=>'不存在']);
         }
         $reply = Message::with(['user'])->where(['rid'=>$res['id']])->select();
         return json(['code'=>200,'data'=>$res ?? [],'reply'=>$reply ?? []]);

    }
    //我的会员  针对代理商
    function myVip(){
       $lists = UserVip::with(['user'])->where("agent_id",request()->adminId)->order("id desc")->select();
       return json(['code'=>200,'data'=>$lists ?? []]);
    }

    //禁用用户

    function disableUser(){
        $uid = $this->params['uid'] ?? 0;
        $w['uid'] = $uid;
        $w['agent_id'] = request()->adminId;
 		$r = UserVip::where($w)->update(['disabled'=>1]);
        return json(['code'=>$r?200:100,'msg'=>$r?'ok':'操作失败或该用户已被禁用']);
    }

    //虚拟充值
    function virtualRecharge(){
        $uid = $this->params['uid'] ?? 0;
        $money = $this->params['money'] ?? 0;
        if($uid == 0 || $money == 0){
        	  return json(['code'=>100,'msg'=>'参数异常']);
        }
        $type = $this->params['type'] ?? '';
        if(!in_array($type,[1,0])){
        	  return json(['code'=>100,'msg'=>'type 参数异常']);
        }

        $uservip = UserVip::where(['uid'=>$uid,'agent_id'=>request()->adminId])->find();
        if(!$uservip){
              return json(['code'=>100,'msg'=>'无权限']);
        }

        if($type == 1){
        	 $r = UserModel::where("id",$uid)->where("id",$uid)->setInc("money_2",$money);
        }else{
        	 $r = UserModel::where("id",$uid)->where("id",$uid)->setDec("money_2",$money);
        }
 		
 		if($r){
 			 $r2 = userService::balanceRecord(['uid'=>$uid,'note'=>'虚拟充值','money'=>$money,'type'=>$type]);
 			 return json(['code'=>$r2?200:100,'msg'=>$r2?'ok':'操作失败']);
 		}
        return json(['code'=>100,'msg'=>'操作失败']);
    }


    //代理商查看下属所有订单

    function order(){
            $res = Order::where('agent_id',request()->adminId)->order("oid desc")->select();
    		return json(['code'=>100,'msg'=>'ok','data'=>$res]);

    }


    //添加分账账户
    function distributionCreate(){
          
          $name = $this->params['nickname'] ?? '';
          $pwd = $this->params['password'] ?? '';
          $phone = $this->params['tel'] ?? '';
          $id = $this->params['id'] ?? 0;
          if($name == '' || $phone == '' || $pwd == ''){
               return json(['code'=>100,'msg'=>"昵称、手机、密码必输填写"]);
          }
          $scene = 'add';
          if($id == 0){
                $data = [
                    'username'=>$phone,
                    'nickname'=>$name,
                    'mobile'=>$phone,
                    'password'=>hash_password($pwd),
                    'agent_id'=>request()->adminId,
                    'access_token'=>generateRandomString(25),
                    'status'=>'enable',
                    'avatar'=>$this->params['avatar'] ?? ''

               ];

          }else{
               $scene = 'edit';
               $data = [
                    'nickname'=>$name,
                    'mobile'=>$phone,
               ];

          }
 

            $validate = new AdminValidate();
            try {
                $validate->scene($scene)->check($data);
            } catch (Throwable $e) {
                $this->error($e->getMessage());
            }

            $model = new Admin();
            $model->startTrans();
            $result = false;
            try {
                if($id > 0){
                     $result = $model->where("id",$id)->update($data);
                     $result = true;
                }else{
                     $result = $model->save($data);
                     $r2 = Db::name('admin_group_access')->insert(['uid'=>$model->id,'group_id'=>8]);
                }
                
                $model->commit();
            } catch (Throwable $e) {
                $model->rollback();
                return json(['code'=>100,'msg'=>$e->getMessage()]);
            }
            
            if($result){
                 return json(['code'=>200,'msg'=>'ok']);
            }else{
                 return json(['code'=>100,'msg'=>'失败']);
            }


         
    }
    // 查看所有分账列表
    function distributionList(){
             $res = Admin::where(['agent_id'=>request()->adminId])->field("id,nickname,mobile")->select();
             return json(['code'=>200,'data'=>$res]);
    }


    // 查看设备 所关联的 分账列表
    function deviceDistributor(){
             $res = DeviceDistributor::with([
                    'distributor' => function($query) {
                        $query->field('id,nickname,mobile'); // 只查询 distributor 的 id,name,email 字段
                    }
             ])->where(['agent_id'=>request()->adminId,'device_id'=>$this->params['device_id']])->select();
             return json(['code'=>200,'data'=>$res]);
    }

    //删除设备绑的分账人
    function delDeviceDistributor(){
          $id = $this->params['id'] ?? 0;
          if($id){
            $d = DeviceDistributor::where(['id'=>$id,'agent_id'=>request()->adminId])->delete();
            if($d){
                 return json(['code'=>200,'msg'=>'ok']);
            }else{
                 return json(['code'=>100,'msg'=>'删除失败']);
            }
          }else{
                return json(['code'=>100,'msg'=>'缺失参数']);
          }
    }

    //针对设备添加分账人
    function addDeviceDistributor(){
            $device_id = $this->params['device_id'] ?? 0;
            $distributor_id = $this->params['distributor_id'] ?? 0;
            $rate = $this->params['rate'] ?? '';
            $device_auth = $this->params['device_auth'] ?? 0;
            $id = $this->params['id'] ?? 0;
            if($device_id == 0){
                $this->error("未绑定设备");
            }
            if($rate == ''){
                $this->error("请输入分账比例");
            }
            if($id == 0){
                if($distributor_id == 0){
                  $this->error("请选择分账人");
                }
                $find = DeviceDistributor::where(['device_id'=>$device_id,'distributor_id'=>$distributor_id])->find();
                if($find){
                    $this->error("该设备已绑定改分账人，请勿重复添加！"); 
                }   
            }

            if($id){
                 $aid = DeviceDistributor::where(['id'=>$id,'agent_id'=>request()->adminId])->update([
                    'rate'=>$rate,
                    'device_auth'=>$device_auth

                 ]);    
            }else{
                 $aid = DeviceDistributor::create([
                    'device_id'=>$device_id,
                    'distributor_id'=>$distributor_id,
                    'agent_id'=>request()->adminId,
                    'rate'=>$rate,
                    'device_auth'=>$device_auth

                 ]);
            }
            
            if($aid){
                 return json(['code'=>200,'msg'=>'ok']);
            }else{
                 return json(['code'=>100,'msg'=>'保存失败']);
            }
            
    }


    //充值设置
    function rechargeSet(){
           $name = $this->params['name'] ?? '';
           $set = $this->params['setting'] ?? '';
           $id = $this->params['id'] ?? 0;
           $admin_id = request()->adminId;
 
           if($name == ''){
               $this->error("名称不能为空");
           }
           if(empty($set)){
               $this->error('配置不能为空');
           }

           $data = [
                'name'=>$name,
                'agent_id'=>$admin_id,
                'setting'=>json_encode($set)
           ];
           if($id){
                $r = RechargeSetting::where(['id'=>$id,'agent_id'=>$admin_id])->update($data);
           }else{
               $find = RechargeSetting::where(['name'=>$name,'agent_id'=>$admin_id])->find();
               if($find){
                     $this->error('同名配置已存在');
               }
               $r = RechargeSetting::create($data);
           }

           
           if($r){
               $this->success("创建成功");
           }else{
               $this->error("创建失败");
           }
           
    }
    function rechargeSetDetail(){
         $id = $this->params['id'] ?? '';
         if($id){
              $find = RechargeSetting::where(['id'=>$id,'agent_id'=>request()->adminId])->find();
              if($find){
                   $find['setting'] = json_decode($find['setting'],true);
                   return json(['code'=>200,'data'=>$find]);
              }else{
                   $this->error("数据不存在");
              }
         }else{
              $this->error("数据不存在");
         }
    }
    // 获取某个充值配置所绑定的场地列表
    function rechargeBangSpace(){
          $rid = $this->params['rid'] ?? 0;
          if($rid){
               $all = RechargeSpace::where("rid",$rid)->column("space_id");
          }
          return json(['code'=>200,'data'=>$all ?? []]);
    }


    //获取充值配置列表
    function rechargeSetList(){
           $admin_id = request()->adminId;
           $res = RechargeSetting::where(['agent_id'=>$admin_id])->select();
           if($res){
               foreach($res as &$v){
                    $v['setting'] = json_decode($v['setting'],true);
               }
           }
           return json(['code'=>200,'data'=>$res ?? []]);
    }
    //绑定场地
    function rechargeBindSpace(){
           $admin_id = request()->adminId;
           $rid =  $this->params['rid'] ?? 0;
           $space_id =  $this->params['space_id'] ?? 0;
           $status = $this->params['status'] ?? 0;
           if($rid == 0 || $space_id == 0){
               $this->error("缺失参数");
           }
           $find = RechargeSetting::where(['agent_id'=>$admin_id,'id'=>$rid])->find();
           if(!$find){
               $this->error("无权限");
           }
           $find = RechargeSpace::where(['space_id'=>$space_id])->find();
           if($find){
                if($find['rid'] != $rid){
                    $this->error("该场地已经绑定过");
                }else{
                    if($status == 1){
                         $this->error("请勿重复绑定");
                    }else{
                          $add = RechargeSpace::where(['space_id'=>$space_id,'rid'=>$rid])->delete();
                    }
                }
           }else{
                   $add = RechargeSpace::create([
                        'rid'=>$rid,
                        'space_id'=>$space_id,
                        'agent_id'=>$admin_id,
                        'status'=>1
                   ]);
           }
           if($add){
                return json(['code'=>200,'msg'=>'ok']);
           }else{
                return json(['code'=>100,'msg'=>'绑定失败']);
           }


    }

    


}